package com.charmzenus.it.common.utils;

import com.charmzenus.it.common.constants.CodeNumber;
import com.charmzenus.it.common.base.MyErrorException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonUtil {

    /**
     * 将JAVA对象转换成JSON字符串
     *
     * @param obj
     * @return
     */
    public static String O2J(Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_NULL);
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new MyErrorException("格式化参数异常", CodeNumber.error_normal);
        }
    }

    /**
     * 将JSON字符串转换成JAVA对象
     *
     * @param obj
     * @param jsonString
     * @return
     */
    public static <T> T J2O(Class<T> obj, String jsonString) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(jsonString, obj);
        } catch (IOException e) {
            throw new MyErrorException("格式化参数异常", CodeNumber.error_normal);
        }
    }

    public static <T> T J2O(TypeReference typeReference,String jsonString) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonString, typeReference);
        } catch (Exception e) {
            throw new MyErrorException("格式化参数异常", CodeNumber.error_normal);
        }
    }
}
